/**
 * 用于生成slidbar
 * Created by Administrator on 2016/1/27.
 */

(function ($) {
    "use strict";
    moment.locale("zh-cn");
    var mainContent = $("#page-content");
    var selectId, table, selectRow, detailTable, lastLoadFxid;

    /**
     * 初始化表格
     */
    function aceSwitch(cellvalue, options, cell) {
        setTimeout(function () {
            $(cell).find('input[type=checkbox]')
                .addClass('ace ace-switch ace-switch-5')
                .after('<span class="lbl"></span>');
        }, 0);
    }

    function updatePagerIcons(table) {
        var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

    /**
     * 初始化日期选择控件
     */
    var initDatepicker = function () {
        $('.date-picker').datepicker({
                startView: 1,
                minViewMode: 1,
                maxViewMode: 1,
                autoclose: true,
                language: 'zh-CN',
                todayHighlight: true
            })
            //show datepicker when clicking on the icon
            .next().on(ace.click_event, function () {
            $(this).prev().focus();
        });
    };

    /**
     * 读取风险详情
     * @param id
     */
    var loadInfo = function (id) {
        $.request(
            $.router.server + "repm/find",
            {
                "type": "post",
                "data": {
                    replyId: id
                },
                "callback": function (data) {
                    for (var i in data) {
                        var d = data[i];
                        for (var j in d) {
                            $("#st2_" + j).val(d[j])
                        }
                    }
                    //$("#st2_filename").html(data[2]["filename"]);
                    //$("#st2_filename").attr("href", $.router.server+"encl/download?id=" + data[2]["id"]);
                    $("#st2_rpid").val(data[0]["id"]);
                    $("#st2_hcsj").val(moment($("#st2_hcsj").val(), "mm-dd-yyyy").format("YYYY-MM"));
                }
            }
        )
    };
    /**
     * 初始化风险列表
     */
    var initGrid = function () {
        selectId = null;
        selectRow = null;
        var grid_selector = "#grid-table";
        var pager_selector = "#grid-pager";
        $(window).on('resize.jqGrid', function () {
            $(grid_selector).jqGrid('setGridWidth', $("#step-container").width());
        });
        //resize on sidebar collapse/expand
        var parent_column = $(grid_selector).closest('[class*="col-"]');
        $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
            if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            }
        });
        $(grid_selector).jqGrid({
            //datatype: "xml",
            //for this example we are using local data
            url: $.router.server + "repm/page",
            mtype: "POST",
            postData: {
                "reply.hcsj": function () {
                    var hcsj = $("#checkDate").val();
                    if (hcsj) {
                        return moment(hcsj, "yyyy-MM").format("YYYY-MM-DD")
                    }
                    return "";
                }
            },
            datatype: "json",
            height: 200,
            colNames: [' ', '风险ID', '风险名称', '核查时间', '反馈时间', '核查结果', '回执文件', '处理状态','操作'],
            colModel: [
                {
                    name: 'id', index: '', width: 80, fixed: true, sortable: false, resize: false,
                    hidden: true
                },
                {
                    name: 'fxid',
                    width: 120,
                    editable: false
                },
                {
                    name: 'fxdmc',
                    width: 250,
                    editable: false
                },
                {
                    name: 'hcsj',
                    index: 'hcsj',
                    width: 120,
                    editable: false,
                    sorttype: "date"
                },
                {
                    name: 'fksj',
                    index: 'fksj',
                    width: 120,
                    editable: false,
                    sorttype: "date",
                    formatter: function (data) {
                        if (data) {
                            return moment(data).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return "";
                    }
                },
                {
                    name: 'gdwfkjg',
                    width: 250,
                    editable: false
                },
                {
                    name: 'enclosures',
                    width: 250,
                    editable: false,
                    formatter: function (data) {
                        if (!data) {
                            return "";
                        }
                        var dom = $("<div />");
                        for (var i in data) {
                            var tpl = [
                                '<a href="'+ $.router.fujiandownload+'?id='+data[i]["id"]+'" id="download-button" class="btn btn-white btn-info btn-bold">',
                                '<i class="ace-icon fa fa-floppy-o bigger-120 blue"></i>',
                                data[i]["filename"],
                                '</a>'
                            ].join('');
                            dom.append(tpl)
                        }
                        return dom.html();
                    }
                },
                {
                    name: 'status',
                    index: 'status',
                    width: 120,
                    editable: false,
                    formatter: function (data) {
                        if (data == 1) {
                            return "处理完成";
                        }
                        return "未处理";
                    }
                },{
                    name:"",
                    width: 120,
                    formatter:function(data,row,rs,e){
                        return [
                            '<button class="btn btn-primary history-action" data-fxid="' + rs.fxid + '" data-hcsj="' + rs.hcsj + '">',
                            '<i class="ace-icon glyphicon glyphicon-search align-top bigger-125"></i>',
                            '查看详情',
                            '</button>'
                        ].join("");
                    }
                }
            ],
            repeatitems: false,
            jsonReader: {
                root: function (data) {
                    var datas = data.datas;
                    var result = [];
                    moment.locale(local);
                    for (var i in datas) {
                        var local = "zh-cn";
                        if ($.checkStartChar(datas[i][0]["hcsj"])) {
                            local = "en";
                        }
                        result.push({
                            "id": datas[i][0]["id"],
                            "fxid": datas[i][0]["fxid"],
                            "fxdmc": datas[i][0]["fxdmc"],
                            "hcsj": moment(datas[i][0]["hcsj"], "MMM dd YYYY").format("YYYY-MM"),
                            "fksj": datas[i][0]["fksj"],
                            "gdwfkjg": datas[i][0]["gdwfkjg"],
                            "enclosures": datas[i][0]["enclosures"],
                            "status": datas[i][0]["status"]
                        });
                    }
                    moment.locale("zh-cn");
                    return result;
                },    // json中代表实际模型数据的入口
                page: "page",    // json中代表当前页码的数据
                total: "pageCount",    // json中代表页码总数的数据
                records: "total" // json中代表数据行总数的数据
            },
            viewrecords: true,
            rowNum: 10,
            //rowList: [10, 20, 30],
            pager: pager_selector,
            altRows: true,
            //toppager: true,

            multiselect: false,
            //multikey: "ctrlKey",
            multiboxonly: false,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    //styleCheckbox(table);
                    //
                    //updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },
            onSelectRow: function (id) {
                selectId = id;
                selectRow = $(this).jqGrid('getRowData', id);
            }
            , autowidth: true
            /**
             ,
             grouping:true,
             groupingView : {
						 groupField : ['name'],
						 groupDataSorted : true,
						 plusicon : 'fa fa-chevron-down bigger-110',
						 minusicon : 'fa fa-chevron-up bigger-110'
					},
             caption: "Grouping"
             */
        });
        table = $(grid_selector);
        //$(window).triggerHandler('resize.jqGrid');
    };
    
    
    
    /**
     * 初始化风险详单表格
     */
    var initDetailGrid = function (fxid,hcsj) {
        //var boot = $("#bootHtml");
        var grid_selector = "#detail-table",
            pager_selector = "#detail-pager";

        // 风险没有变化,不需要重新初始化表格
        //if(lastLoadFxid==selectRow["fxid"]){
        //    detailTable.trigger("reloadGrid");
        //    return
        //}
        //lastLoadFxid = selectRow["fxid"];
        // 每种风险表格不同,清理现场
        //$(grid_selector).jqGrid('GridDestroy','detail-table');
        //$(boot).empty();
        //$(boot).append('<table id="detail-table"></table>');
        //$(boot).append('<div id="detail-pager"></div>');

        // 获取风险结构
        $.request(
            $.router.server + "repm/get_risk",
            {
                "type": "post",
                "data": {
                    fxid: fxid
                },
                "callback": function (data) {
                    if (data.success == false) {
                        bootbox.dialog({
                            message: data.message,
                            buttons: {
                                "success": {
                                    "label": "确定",
                                    "className": "btn-sm btn-primary"
                                }
                            }
                        });
                        return;
                    }
                    var columns = data["columns"],
                        colNames = [],
                        colModel = [];
                    for (var i in columns) {
                        if(!columns.hasOwnProperty(i)){
                            continue;
                        }
                        colNames.push(columns[i]["name"]);
                        colModel.push({
                            "name": columns[i]["id"]
                        })
                    }

                    $(window).on('resize.jqGrid', function () {
                        $(grid_selector).jqGrid('setGridWidth', $("#step-container").width());
                    });
                    //resize on sidebar collapse/expand
                    var parent_column = $(grid_selector).closest('[class*="col-"]');
                    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                        if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                        }
                    });
                    $(grid_selector).jqGrid({
                        //datatype: "xml",
                        //for this example we are using local data
                        url: $.router.server + "repm/detail_risk",
                        mtype: "POST",
                        postData: {
                            "fxid": fxid,
                            "cycle": hcsj
                        },
                        datatype: "json",
                        height: 400,
                        colNames: colNames,
                        colModel: colModel,
                        repeatitems: false,
                        jsonReader: {
                            root: "datas",    // json中代表实际模型数据的入口
                            page: "page",    // json中代表当前页码的数据
                            total: "pageCount",    // json中代表页码总数的数据
                            records: "total" // json中代表数据行总数的数据
                        },
                        viewrecords: true,
                        rowNum: 10,
                        //rowList: [10, 20, 30],
                        pager: pager_selector,
                        altRows: true,
                        //toppager: true,

                        multiselect: false,
                        //multikey: "ctrlKey",
                        multiboxonly: false,

                        loadComplete: function () {
                            var table = this;
                            setTimeout(function () {
                                //styleCheckbox(table);
                                //
                                //updateActionIcons(table);
                                updatePagerIcons(table);
                                enableTooltips(table);
                            }, 0);
                        },
                        autowidth: true
                    });
                    detailTable = $(grid_selector);
                    $(window).triggerHandler('resize.jqGrid');
                }
            }
        );
    };
    var showDetailBox = function(){
        var fxid = $(this).data("fxid");
        var hcsj = $(this).data("hcsj");
        var dialog = bootbox.dialog({
                title: "风险明细",
                size: "large",
                message: '<table id="detail-table"></table><div id="detail-pager"></div>',
                onEscape: function () {
                    $("#detail-table").jqGrid('GridDestroy', 'detail-table')
                },
                buttons: {
                    download: {
                        label: "下载",
                        className: "btn-info fa fa-download",
                        callback: function () {
                            var elemIF = document.createElement("iframe");
                            elemIF.src = $.router.server+"repm/detail_risk_download?fxid="+fxid+"&cycle="+hcsj;
                            elemIF.style.display = "none";
                            document.body.appendChild(elemIF);
                            $(elemIF).ready(function(){
                                $(this).remove();
                            });
                        }
                    },
                    success: {
                        label: "关闭",
                        className: "btn-success",
                        callback: function () {
                            $("#detail-table").jqGrid('GridDestroy', 'detail-table')
                        }
                    }
                }
            }
        ).init(function () {
            $('.modal-dialog').css({
                width:"80%"
            });
            $('.modal-body').css({
                overflow:"auto"
            });
            initDetailGrid(fxid,hcsj);
        });
    };
    var pageReady = function () {

        $('#fuelux-wizard')
            .ace_wizard({})
            .on('change', function (e, info) {
                if (!selectId) {
                    bootbox.dialog({
                        message: "请选中一行进行处理",
                        buttons: {
                            "success": {
                                "label": "关闭",
                                "className": "btn-sm btn-primary"
                            }
                        }
                    });
                    return false;
                }
                if (info.step == 1 && info.direction == "next") {
                    loadInfo(selectId);
                }
            })
            .on('changed', function (e) {
                // wizard changed fin.
            })
            .on('finished', function (e) {
                if (!$('#validation-form').valid()) return false;
                $.request(
                    $.router.server + "repm/save",
                    {
                        "type": "post",
                        "data": $('#validation-form').serializeArray(),
                        "callback": function (data) {
                            if (data.success) {
                                bootbox.dialog({
                                    message: "处理完成",
                                    buttons: {
                                        "success": {
                                            "label": "确定",
                                            "className": "btn-sm btn-primary",
                                            "callback": function () {
                                                table.trigger("reloadGrid");
                                                var wizard = $('#fuelux-wizard').data('wizard');
                                                wizard.currentStep = 1;
                                                wizard.setState();
                                            }
                                        }
                                    }
                                });
                            } else {
                                bootbox.dialog({
                                    message: data.message,
                                    buttons: {
                                        "success": {
                                            "label": "确定",
                                            "className": "btn-sm btn-primary",
                                        }
                                    }
                                });
                            }
                        }
                    }
                );
            }).on('stepclick', function (e) {
            //e.preventDefault();//this will prevent clicking and selecting steps
        });

        //jump to a step
        $('#step-jump').on('click', function () {
            var wizard = $('#fuelux-wizard').data('wizard');
            wizard.currentStep = 3;
            wizard.setState();
        });

        $.mask.definitions['~'] = '[+-]';

        initGrid();
        initDatepicker();
        /**
         $('#date').datepicker({autoclose:true}).on('changeDate', function(ev) {
					$(this).closest('form').validate().element($(this));
				});

         $('#mychosen').chosen().on('change', function(ev) {
					$(this).closest('form').validate().element($(this));
				});
         */
    };
    mainContent.on("pageshow.0304", function () {
        if (mainContent.find("[data-page=history-page]").length > 0) {
            pageReady();
        }
    });
    $(document).on("click", "#button-search", function () {
        table.trigger("reloadGrid");
    });
    $(document).on("click.history-action",".history-action",showDetailBox);
})(jQuery);
